package com.cjc.express.controller;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
 * ========================
 * Created with intellij IDEA
 * 创建者：杜一平
 * 日期：2017/1/19（星期五）
 * 时间：08：00
 * 说明：该类为下面的控制器提供解析json工具
 * ==========================
 */

public class BaseController {
    private final static Logger logger = LoggerFactory.getLogger(UserController.class);
    /*
    * 接收json对象
    */
    public JsonObject getJsonObject(HttpServletRequest request) throws IOException {
        String jsonString = getStrFromInsByCode(request.getInputStream(), "utf-8");
        logger.info("request:"+jsonString);
        JsonParser jsonParser = new JsonParser();
        return (JsonObject) jsonParser.parse(jsonString);
    }
    /*
     * 接收json数组
     */
    public JsonArray getJsonArray(HttpServletRequest request) throws IOException {
        String jsonString = getStrFromInsByCode(request.getInputStream(), "utf-8");
        logger.info("request:"+jsonString);
        JsonParser jsonParser = new JsonParser();
        return (JsonArray) jsonParser.parse(jsonString);
    }
    public static String getStrFromInsByCode(InputStream is, String code){
        StringBuilder builder=new StringBuilder();
        BufferedReader reader=null;

        try {
            reader = new BufferedReader(new InputStreamReader(is,code));
            String line;
            while((line=reader.readLine())!=null){
                builder.append(line+"\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return builder.toString();
    }
}
